home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_emacs.idb / usr / freeware / share / emacs / 19.34 / lisp / shell.el.z / shell.el
Encoding:
Text File  |  1998-10-28  |  34.4 KB  |  853 lines

  1. ;;; shell.el --- specialized comint.el for running the shell.
  2.  
  3. ;; Copyright (C) 1988, 1993, 1994, 1995, 1996 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Olin Shivers <shivers@cs.cmu.edu>
  6. ;; Maintainer: Simon Marshall <simon@gnu.ai.mit.edu>
  7. ;; Keywords: processes
  8.  
  9. ;; This file is part of GNU Emacs.
  10.  
  11. ;; GNU Emacs is free software; you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 2, or (at your option)
  14. ;; any later version.
  15.  
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. ;; GNU General Public License for more details.
  20.  
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  23. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  24. ;; Boston, MA 02111-1307, USA.
  25.  
  26. ;;; Commentary:
  27.  
  28. ;; Please send me bug reports, bug fixes, and extensions, so that I can
  29. ;; merge them into the master source.
  30. ;;     - Olin Shivers (shivers@cs.cmu.edu)
  31. ;;     - Simon Marshall (simon@gnu.ai.mit.edu)
  32.  
  33. ;; This file defines a a shell-in-a-buffer package (shell mode) built
  34. ;; on top of comint mode.  This is actually cmushell with things
  35. ;; renamed to replace its counterpart in Emacs 18.  cmushell is more
  36. ;; featureful, robust, and uniform than the Emacs 18 version.
  37.  
  38. ;; Since this mode is built on top of the general command-interpreter-in-
  39. ;; a-buffer mode (comint mode), it shares a common base functionality, 
  40. ;; and a common set of bindings, with all modes derived from comint mode.
  41. ;; This makes these modes easier to use.
  42.  
  43. ;; For documentation on the functionality provided by comint mode, and
  44. ;; the hooks available for customising it, see the file comint.el.
  45. ;; For further information on shell mode, see the comments below.
  46.  
  47. ;; Needs fixin:
  48. ;; When sending text from a source file to a subprocess, the process-mark can 
  49. ;; move off the window, so you can lose sight of the process interactions.
  50. ;; Maybe I should ensure the process mark is in the window when I send
  51. ;; text to the process? Switch selectable?
  52.  
  53. ;; YOUR .EMACS FILE
  54. ;;=============================================================================
  55. ;; Some suggestions for your .emacs file.
  56. ;;
  57. ;; ;; Define M-# to run some strange command:
  58. ;; (eval-after-load "shell"
  59. ;;  '(define-key shell-mode-map "\M-#" 'shells-dynamic-spell))
  60.  
  61. ;; Brief Command Documentation:
  62. ;;============================================================================
  63. ;; Comint Mode Commands: (common to shell and all comint-derived modes)
  64. ;;
  65. ;; m-p        comint-previous-input            Cycle backwards in input history
  66. ;; m-n        comint-next-input                  Cycle forwards
  67. ;; m-r     comint-previous-matching-input  Previous input matching a regexp
  68. ;; m-s     comint-next-matching-input      Next input that matches
  69. ;; m-c-l   comint-show-output            Show last batch of process output
  70. ;; return  comint-send-input
  71. ;; c-d        comint-delchar-or-maybe-eof        Delete char unless at end of buff.
  72. ;; c-c c-a comint-bol                      Beginning of line; skip prompt
  73. ;; c-c c-u comint-kill-input                ^u
  74. ;; c-c c-w backward-kill-word            ^w
  75. ;; c-c c-c comint-interrupt-subjob         ^c
  76. ;; c-c c-z comint-stop-subjob                ^z
  77. ;; c-c c-\ comint-quit-subjob                ^\
  78. ;; c-c c-o comint-kill-output            Delete last batch of process output
  79. ;; c-c c-r comint-show-output            Show last batch of process output
  80. ;; c-c c-h comint-dynamic-list-input-ring  List input history
  81. ;;         send-invisible                  Read line w/o echo & send to proc
  82. ;;         comint-continue-subjob        Useful if you accidentally suspend
  83. ;;                            top-level job
  84. ;; comint-mode-hook is the comint mode hook.
  85.  
  86. ;; Shell Mode Commands:
  87. ;;         shell            Fires up the shell process
  88. ;; tab     comint-dynamic-complete    Complete filename/command/history
  89. ;; m-?     comint-dynamic-list-filename-completions
  90. ;;                    List completions in help buffer
  91. ;; m-c-f   shell-forward-command    Forward a shell command
  92. ;; m-c-b   shell-backward-command    Backward a shell command
  93. ;;         dirs            Resync the buffer's dir stack
  94. ;;         dirtrack-toggle        Turn dir tracking on/off
  95. ;;         comint-strip-ctrl-m        Remove trailing ^Ms from output
  96. ;;
  97. ;; The shell mode hook is shell-mode-hook
  98. ;; comint-prompt-regexp is initialised to shell-prompt-pattern, for backwards
  99. ;; compatibility.
  100.  
  101. ;; Read the rest of this file for more information.
  102.  
  103. ;;; Code:
  104.  
  105. (require 'comint)
  106.  
  107. ;;; Customization and Buffer Variables
  108.  
  109. ;;;###autoload
  110. (defvar shell-prompt-pattern "^[^#$%>\n]*[#$%>] *"
  111.   "Regexp to match prompts in the inferior shell.
  112. Defaults to \"^[^#$%>\\n]*[#$%>] *\", which works pretty well.
  113. This variable is used to initialise `comint-prompt-regexp' in the 
  114. shell buffer.
  115.  
  116. The pattern should probably not match more than one line.  If it does,
  117. Shell mode may become confused trying to distinguish prompt from input
  118. on lines which don't start with a prompt.
  119.  
  120. This is a fine thing to set in your `.emacs' file.")
  121.  
  122. (defvar shell-completion-fignore nil
  123.   "*List of suffixes to be disregarded during file/command completion.
  124. This variable is used to initialize `comint-completion-fignore' in the shell
  125. buffer.  The default is nil, for compatibility with most shells.
  126. Some people like (\"~\" \"#\" \"%\").
  127.  
  128. This is a fine thing to set in your `.emacs' file.")  
  129.  
  130. (defvar shell-delimiter-argument-list '(?\| ?& ?< ?> ?\( ?\) ?\;)
  131.   "List of characters to recognise as separate arguments.
  132. This variable is used to initialize `comint-delimiter-argument-list' in the
  133. shell buffer.  The value may depend on the operating system or shell.
  134.  
  135. This is a fine thing to set in your `.emacs' file.")
  136.  
  137. (defvar shell-file-name-chars
  138.   (if (memq system-type '(ms-dos windows-nt))
  139.       "~/A-Za-z0-9_^$!#%&{}@`'.()-"
  140.     "~/A-Za-z0-9+@:_.$#%,={}-")
  141.   "String of characters valid in a file name.
  142. This variable is used to initialize `comint-file-name-chars' in the
  143. shell buffer.  The value may depend on the operating system or shell.
  144.  
  145. This is a fine thing to set in your `.emacs' file.")
  146.  
  147. (defvar shell-file-name-quote-list
  148.   (if (memq system-type '(ms-dos windows-nt))
  149.       nil
  150.     (append shell-delimiter-argument-list '(?\  ?\* ?\! ?\" ?\' ?\`)))
  151.   "List of characters to quote when in a file name.
  152. This variable is used to initialize `comint-file-name-quote-list' in the
  153. shell buffer.  The value may depend on the operating system or shell.
  154.  
  155. This is a fine thing to set in your `.emacs' file.")
  156.  
  157. (defvar shell-dynamic-complete-functions
  158.   '(comint-replace-by-expanded-history
  159.     shell-dynamic-complete-environment-variable
  160.     shell-dynamic-complete-command
  161.     shell-replace-by-expanded-directory
  162.     comint-dynamic-complete-filename)
  163.   "List of functions called to perform completion.
  164. This variable is used to initialise `comint-dynamic-complete-functions' in the
  165. shell buffer.
  166.  
  167. This is a fine thing to set in your `.emacs' file.")
  168.  
  169. (defvar shell-command-regexp "[^;&|\n]+"
  170.   "*Regexp to match a single command within a pipeline.
  171. This is used for directory tracking and does not do a perfect job.")
  172.  
  173. (defvar shell-completion-execonly t
  174.   "*If non-nil, use executable files only for completion candidates.
  175. This mirrors the optional behavior of tcsh.
  176.  
  177. Detecting executability of files may slow command completion considerably.")
  178.  
  179. (defvar shell-popd-regexp "popd"
  180.   "*Regexp to match subshell commands equivalent to popd.")
  181.  
  182. (defvar shell-pushd-regexp "pushd"
  183.   "*Regexp to match subshell commands equivalent to pushd.")
  184.  
  185. (defvar shell-pushd-tohome nil
  186.   "*If non-nil, make pushd with no arg behave as \"pushd ~\" (like cd).
  187. This mirrors the optional behavior of tcsh.")
  188.  
  189. (defvar shell-pushd-dextract nil
  190.   "*If non-nil, make \"pushd +n\" pop the nth dir to the stack top.
  191. This mirrors the optional behavior of tcsh.")
  192.  
  193. (defvar shell-pushd-dunique nil
  194.   "*If non-nil, make pushd only add unique directories to the stack.
  195. This mirrors the optional behavior of tcsh.")
  196.  
  197. (defvar shell-cd-regexp "cd"
  198.   "*Regexp to match subshell commands equivalent to cd.")
  199.  
  200. (defvar shell-chdrive-regexp
  201.   (if (memq system-type '(ms-dos windows-nt)) 
  202.       ; NetWare allows the five chars between upper and lower alphabetics.
  203.       "[]a-zA-Z^_`\\[\\\\]:"
  204.     nil)
  205.   "*If non-nil, is regexp used to track drive changes.")
  206.  
  207. (defvar explicit-shell-file-name nil
  208.   "*If non-nil, is file name to use for explicitly requested inferior shell.")
  209.  
  210. (defvar explicit-csh-args
  211.   (if (eq system-type 'hpux)
  212.       ;; -T persuades HP's csh not to think it is smarter
  213.       ;; than us about what terminal modes to use.
  214.       '("-i" "-T")
  215.     '("-i"))
  216.   "*Args passed to inferior shell by M-x shell, if the shell is csh.
  217. Value is a list of strings, which may be nil.")
  218.  
  219. (defvar shell-input-autoexpand 'history
  220.   "*If non-nil, expand input command history references on completion.
  221. This mirrors the optional behavior of tcsh (its autoexpand and histlit).
  222.  
  223. If the value is `input', then the expansion is seen on input.
  224. If the value is `history', then the expansion is only when inserting
  225. into the buffer's input ring.  See also `comint-magic-space' and
  226. `comint-dynamic-complete'.
  227.  
  228. This variable supplies a default for `comint-input-autoexpand',
  229. for Shell mode only.")
  230.  
  231. (defvar shell-dirstack nil
  232.   "List of directories saved by pushd in this buffer's shell.
  233. Thus, this does not include the shell's current directory.")
  234.  
  235. (defvar shell-dirtrackp t
  236.   "Non-nil in a shell buffer means directory tracking is enabled.")
  237.  
  238. (defvar shell-last-dir nil
  239.   "Keep track of last directory for ksh `cd -' command.")
  240.  
  241. (defvar shell-dirstack-query nil
  242.   "Command used by `shell-resync-dir' to query the shell.")
  243.  
  244. (defvar shell-mode-map nil)
  245. (cond ((not shell-mode-map)
  246.        (setq shell-mode-map (nconc (make-sparse-keymap) comint-mode-map))
  247.        (define-key shell-mode-map "\C-c\C-f" 'shell-forward-command)
  248.        (define-key shell-mode-map "\C-c\C-b" 'shell-backward-command)
  249.        (define-key shell-mode-map "\t" 'comint-dynamic-complete)
  250.        (define-key shell-mode-map "\M-?"
  251.      'comint-dynamic-list-filename-completions)
  252.        (define-key shell-mode-map [menu-bar completion]
  253.      (copy-keymap (lookup-key comint-mode-map [menu-bar completion])))
  254.        (define-key-after (lookup-key shell-mode-map [menu-bar completion])
  255.      [complete-env-variable] '("Complete Env. Variable Name" .
  256.                    shell-dynamic-complete-environment-variable)
  257.      'complete-file)
  258.        (define-key-after (lookup-key shell-mode-map [menu-bar completion])
  259.      [expand-directory] '("Expand Directory Reference" .
  260.                   shell-replace-by-expanded-directory)
  261.      'complete-expand)))
  262.  
  263. (defvar shell-mode-hook '()
  264.   "*Hook for customising Shell mode.")
  265.  
  266. (defvar shell-font-lock-keywords
  267.   (list (cons shell-prompt-pattern 'font-lock-keyword-face)
  268.     '("[ \t]\\([+-][^ \t\n]+\\)" 1 font-lock-comment-face)
  269.     '("^[^ \t\n]+:.*" . font-lock-string-face)
  270.     '("^\\[[1-9][0-9]*\\]" . font-lock-string-face))
  271.   "Additional expressions to highlight in Shell mode.")
  272.  
  273. ;;; Basic Procedures
  274.  
  275. (defun shell-mode ()
  276.   "Major mode for interacting with an inferior shell.
  277. \\[comint-send-input] after the end of the process' output sends the text from
  278.     the end of process to the end of the current line.
  279. \\[comint-send-input] before end of process output copies the current line minus the prompt to
  280.     the end of the buffer and sends it (\\[comint-copy-old-input] just copies the current line).
  281. \\[send-invisible] reads a line of text without echoing it, and sends it to
  282.     the shell.  This is useful for entering passwords.  Or, add the function
  283.     `comint-watch-for-password-prompt' to `comint-output-filter-functions'.
  284.  
  285. If you want to make multiple shell buffers, rename the `*shell*' buffer
  286. using \\[rename-buffer] or \\[rename-uniquely] and start a new shell.
  287.  
  288. If you want to make shell buffers limited in length, add the function
  289. `comint-truncate-buffer' to `comint-output-filter-functions'.
  290.  
  291. If you accidentally suspend your process, use \\[comint-continue-subjob]
  292. to continue it.
  293.  
  294. `cd', `pushd' and `popd' commands given to the shell are watched by Emacs to
  295. keep this buffer's default directory the same as the shell's working directory.
  296. While directory tracking is enabled, the shell's working directory is displayed
  297. by \\[list-buffers] or \\[mouse-buffer-menu] in the `File' field.
  298. \\[dirs] queries the shell and resyncs Emacs' idea of what the current 
  299.     directory stack is.
  300. \\[dirtrack-toggle] turns directory tracking on and off.
  301.  
  302. \\{shell-mode-map}
  303. Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
  304. `shell-mode-hook' (in that order).  Before each input, the hooks on
  305. `comint-input-filter-functions' are run.  After each shell output, the hooks
  306. on `comint-output-filter-functions' are run.
  307.  
  308. Variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp' 
  309. and `shell-popd-regexp' are used to match their respective commands, 
  310. while `shell-pushd-tohome', `shell-pushd-dextract' and `shell-pushd-dunique' 
  311. control the behavior of the relevant command.
  312.  
  313. Variables `comint-completion-autolist', `comint-completion-addsuffix',
  314. `comint-completion-recexact' and `comint-completion-fignore' control the
  315. behavior of file name, command name and variable name completion.  Variable
  316. `shell-completion-execonly' controls the behavior of command name completion.
  317. Variable `shell-completion-fignore' is used to initialise the value of
  318. `comint-completion-fignore'.
  319.  
  320. Variables `comint-input-ring-file-name' and `comint-input-autoexpand' control
  321. the initialisation of the input ring history, and history expansion.
  322.  
  323. Variables `comint-output-filter-functions', a hook, and
  324. `comint-scroll-to-bottom-on-input' and `comint-scroll-to-bottom-on-output'
  325. control whether input and output cause the window to scroll to the end of the
  326. buffer."
  327.   (interactive)
  328.   (comint-mode)
  329.   (setq major-mode 'shell-mode)
  330.   (setq mode-name "Shell")
  331.   (use-local-map shell-mode-map)
  332.   (setq comint-prompt-regexp shell-prompt-pattern)
  333.   (setq comint-completion-fignore shell-completion-fignore)
  334.   (setq comint-delimiter-argument-list shell-delimiter-argument-list)
  335.   (setq comint-file-name-chars shell-file-name-chars)
  336.   (setq comint-file-name-quote-list shell-file-name-quote-list)
  337.   (setq comint-dynamic-complete-functions shell-dynamic-complete-functions)
  338.   (make-local-variable 'paragraph-start)
  339.   (setq paragraph-start comint-prompt-regexp)
  340.   (make-local-variable 'font-lock-defaults)
  341.   (setq font-lock-defaults '(shell-font-lock-keywords t))
  342.   (make-local-variable 'shell-dirstack)
  343.   (setq shell-dirstack nil)
  344.   (setq shell-last-dir nil)
  345.   (make-local-variable 'shell-dirtrackp)
  346.   (setq shell-dirtrackp t)
  347.   (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
  348.   (setq comint-input-autoexpand shell-input-autoexpand)
  349.   (make-local-variable 'list-buffers-directory)
  350.   (setq list-buffers-directory (expand-file-name default-directory))
  351.   ;; shell-dependent assignments.
  352.   (let ((shell (file-name-nondirectory (car
  353.          (process-command (get-buffer-process (current-buffer)))))))
  354.     (setq comint-input-ring-file-name
  355.       (or (getenv "HISTFILE")
  356.           (cond ((string-equal shell "bash") "~/.bash_history")
  357.             ((string-equal shell "ksh") "~/.sh_history")
  358.             (t "~/.history"))))
  359.     (if (or (equal comint-input-ring-file-name "")
  360.         (equal (file-truename comint-input-ring-file-name) "/dev/null"))
  361.     (setq comint-input-ring-file-name nil))
  362.     (setq shell-dirstack-query
  363.       (cond ((string-equal shell "sh") "pwd")
  364.         ((string-equal shell "ksh") "echo $PWD ~-")
  365.         (t "dirs"))))
  366.   (run-hooks 'shell-mode-hook)
  367.   (comint-read-input-ring t))
  368.  
  369. ;;;###autoload
  370. (defun shell ()
  371.   "Run an inferior shell, with I/O through buffer *shell*.
  372. If buffer exists but shell process is not running, make new shell.
  373. If buffer exists and shell process is running, just switch to buffer `*shell*'.
  374. Program used comes from variable `explicit-shell-file-name',
  375.  or (if that is nil) from the ESHELL environment variable,
  376.  or else from SHELL if there is no ESHELL.
  377. If a file `~/.emacs_SHELLNAME' exists, it is given as initial input
  378.  (Note that this may lose due to a timing error if the shell
  379.   discards input when it starts up.)
  380. The buffer is put in Shell mode, giving commands for sending input
  381. and controlling the subjobs of the shell.  See `shell-mode'.
  382. See also the variable `shell-prompt-pattern'.
  383.  
  384. The shell file name (sans directories) is used to make a symbol name
  385. such as `explicit-csh-args'.  If that symbol is a variable,
  386. its value is used as a list of arguments when invoking the shell.
  387. Otherwise, one argument `-i' is passed to the shell.
  388.  
  389. \(Type \\[describe-mode] in the shell buffer for a list of commands.)"
  390.   (interactive)
  391.   (if (not (comint-check-proc "*shell*"))
  392.       (let* ((prog (or explicit-shell-file-name
  393.                (getenv "ESHELL")
  394.                (getenv "SHELL")
  395.                "/bin/sh"))             
  396.          (name (file-name-nondirectory prog))
  397.          (startfile (concat "~/.emacs_" name))
  398.          (xargs-name (intern-soft (concat "explicit-" name "-args")))
  399.          shell-buffer)
  400.     (save-excursion
  401.       (set-buffer (apply 'make-comint "shell" prog
  402.                  (if (file-exists-p startfile) startfile)
  403.                  (if (and xargs-name (boundp xargs-name))
  404.                  (symbol-value xargs-name)
  405.                    '("-i"))))
  406.       (setq shell-buffer (current-buffer))
  407.       (shell-mode))
  408.     (pop-to-buffer shell-buffer))
  409.     (pop-to-buffer "*shell*")))
  410.  
  411. ;;; Don't do this when shell.el is loaded, only while dumping.
  412. ;;;###autoload (add-hook 'same-window-buffer-names "*shell*")
  413.  
  414. ;;; Directory tracking
  415. ;;;
  416. ;;; This code provides the shell mode input sentinel
  417. ;;;     SHELL-DIRECTORY-TRACKER
  418. ;;; that tracks cd, pushd, and popd commands issued to the shell, and
  419. ;;; changes the current directory of the shell buffer accordingly.
  420. ;;;
  421. ;;; This is basically a fragile hack, although it's more accurate than
  422. ;;; the version in Emacs 18's shell.el. It has the following failings:
  423. ;;; 1. It doesn't know about the cdpath shell variable.
  424. ;;; 2. It cannot infallibly deal with command sequences, though it does well
  425. ;;;    with these and with ignoring commands forked in another shell with ()s.
  426. ;;; 3. More generally, any complex command is going to throw it. Otherwise,
  427. ;;;    you'd have to build an entire shell interpreter in emacs lisp.  Failing
  428. ;;;    that, there's no way to catch shell commands where cd's are buried
  429. ;;;    inside conditional expressions, aliases, and so forth.
  430. ;;;
  431. ;;; The whole approach is a crock. Shell aliases mess it up. File sourcing
  432. ;;; messes it up. You run other processes under the shell; these each have
  433. ;;; separate working directories, and some have commands for manipulating
  434. ;;; their w.d.'s (e.g., the lcd command in ftp). Some of these programs have
  435. ;;; commands that do *not* affect the current w.d. at all, but look like they
  436. ;;; do (e.g., the cd command in ftp).  In shells that allow you job
  437. ;;; control, you can switch between jobs, all having different w.d.'s. So
  438. ;;; simply saying %3 can shift your w.d..
  439. ;;;
  440. ;;; The solution is to relax, not stress out about it, and settle for
  441. ;;; a hack that works pretty well in typical circumstances. Remember
  442. ;;; that a half-assed solution is more in keeping with the spirit of Unix, 
  443. ;;; anyway. Blech.
  444. ;;;
  445. ;;; One good hack not implemented here for users of programmable shells
  446. ;;; is to program up the shell w.d. manipulation commands to output
  447. ;;; a coded command sequence to the tty. Something like
  448. ;;;     ESC | <cwd> |
  449. ;;; where <cwd> is the new current working directory. Then trash the
  450. ;;; directory tracking machinery currently used in this package, and
  451. ;;; replace it with a process filter that watches for and strips out
  452. ;;; these messages.
  453.  
  454. (defun shell-directory-tracker (str)
  455.   "Tracks cd, pushd and popd commands issued to the shell.
  456. This function is called on each input passed to the shell.
  457. It watches for cd, pushd and popd commands and sets the buffer's
  458. default directory to track these commands.
  459.  
  460. You may toggle this tracking on and off with M-x dirtrack-toggle.
  461. If emacs gets confused, you can resync with the shell with M-x dirs.
  462.  
  463. See variables `shell-cd-regexp', `shell-chdrive-regexp', `shell-pushd-regexp',
  464. and  `shell-popd-regexp', while `shell-pushd-tohome', `shell-pushd-dextract', 
  465. and `shell-pushd-dunique' control the behavior of the relevant command.
  466.  
  467. Environment variables are expanded, see function `substitute-in-file-name'."
  468.   (if shell-dirtrackp
  469.       ;; We fail gracefully if we think the command will fail in the shell.
  470.       (condition-case chdir-failure
  471.       (let ((start (progn (string-match "^[; \t]*" str) ; skip whitespace
  472.                   (match-end 0)))
  473.         end cmd arg1)
  474.         (while (string-match shell-command-regexp str start)
  475.           (setq end (match-end 0)
  476.             cmd (comint-arguments (substring str start end) 0 0)
  477.             arg1 (comint-arguments (substring str start end) 1 1))
  478.           (cond ((string-match (concat "\\`\\(" shell-popd-regexp
  479.                        "\\)\\($\\|[ \t]\\)")
  480.                    cmd)
  481.              (shell-process-popd (comint-substitute-in-file-name arg1)))
  482.             ((string-match (concat "\\`\\(" shell-pushd-regexp
  483.                        "\\)\\($\\|[ \t]\\)")
  484.                    cmd)
  485.              (shell-process-pushd (comint-substitute-in-file-name arg1)))
  486.             ((string-match (concat "\\`\\(" shell-cd-regexp
  487.                        "\\)\\($\\|[ \t]\\)")
  488.                    cmd)
  489.              (shell-process-cd (comint-substitute-in-file-name arg1)))
  490.             ((and shell-chdrive-regexp
  491.               (string-match (concat "\\`\\(" shell-chdrive-regexp
  492.                         "\\)\\($\\|[ \t]\\)")
  493.                     cmd))
  494.              (shell-process-cd (comint-substitute-in-file-name cmd))))
  495.           (setq start (progn (string-match "[; \t]*" str end) ; skip again
  496.                  (match-end 0)))))
  497.     (error "Couldn't cd"))))
  498.  
  499. ;;; popd [+n]
  500. (defun shell-process-popd (arg)
  501.   (let ((num (or (shell-extract-num arg) 0)))
  502.     (cond ((and num (= num 0) shell-dirstack)
  503.        (shell-cd (car shell-dirstack))
  504.        (setq shell-dirstack (cdr shell-dirstack))
  505.        (shell-dirstack-message))
  506.       ((and num (> num 0) (<= num (length shell-dirstack)))
  507.        (let* ((ds (cons nil shell-dirstack))
  508.           (cell (nthcdr (1- num) ds)))
  509.          (rplacd cell (cdr (cdr cell)))
  510.          (setq shell-dirstack (cdr ds))
  511.          (shell-dirstack-message)))
  512.       (t
  513.        (error "Couldn't popd")))))
  514.  
  515. ;; Return DIR prefixed with comint-file-name-prefix as appropriate.
  516. (defun shell-prefixed-directory-name (dir)
  517.   (if (= (length comint-file-name-prefix) 0)
  518.       dir
  519.     (if (file-name-absolute-p dir)
  520.     ;; The name is absolute, so prepend the prefix.
  521.     (concat comint-file-name-prefix dir)
  522.       ;; For relative name we assume default-directory already has the prefix.
  523.       (expand-file-name dir))))
  524.  
  525. ;;; cd [dir]
  526. (defun shell-process-cd (arg)
  527.   (let ((new-dir (cond ((zerop (length arg)) (concat comint-file-name-prefix
  528.                              "~"))
  529.                ((string-equal "-" arg) shell-last-dir)
  530.                (t (shell-prefixed-directory-name arg)))))
  531.     (setq shell-last-dir default-directory)
  532.     (shell-cd new-dir)
  533.     (shell-dirstack-message)))
  534.  
  535. ;;; pushd [+n | dir]
  536. (defun shell-process-pushd (arg)
  537.   (let ((num (shell-extract-num arg)))
  538.     (cond ((zerop (length arg))
  539.        ;; no arg -- swap pwd and car of stack unless shell-pushd-tohome
  540.        (cond (shell-pushd-tohome
  541.           (shell-process-pushd (concat comint-file-name-prefix "~")))
  542.          (shell-dirstack
  543.           (let ((old default-directory))
  544.             (shell-cd (car shell-dirstack))
  545.             (setq shell-dirstack (cons old (cdr shell-dirstack)))
  546.             (shell-dirstack-message)))
  547.          (t
  548.           (message "Directory stack empty."))))
  549.       ((numberp num)
  550.        ;; pushd +n
  551.        (cond ((> num (length shell-dirstack))
  552.           (message "Directory stack not that deep."))
  553.          ((= num 0)
  554.           (error (message "Couldn't cd.")))
  555.          (shell-pushd-dextract
  556.           (let ((dir (nth (1- num) shell-dirstack)))
  557.             (shell-process-popd arg)
  558.             (shell-process-pushd default-directory)
  559.             (shell-cd dir)
  560.             (shell-dirstack-message)))
  561.          (t
  562.           (let* ((ds (cons default-directory shell-dirstack))
  563.              (dslen (length ds))
  564.              (front (nthcdr num ds))
  565.              (back (reverse (nthcdr (- dslen num) (reverse ds))))
  566.              (new-ds (append front back)))
  567.             (shell-cd (car new-ds))
  568.             (setq shell-dirstack (cdr new-ds))
  569.             (shell-dirstack-message)))))
  570.       (t
  571.        ;; pushd <dir>
  572.        (let ((old-wd default-directory))
  573.          (shell-cd (shell-prefixed-directory-name arg))
  574.          (if (or (null shell-pushd-dunique)
  575.              (not (member old-wd shell-dirstack)))
  576.          (setq shell-dirstack (cons old-wd shell-dirstack)))
  577.          (shell-dirstack-message))))))
  578.  
  579. ;; If STR is of the form +n, for n>0, return n. Otherwise, nil.
  580. (defun shell-extract-num (str)
  581.   (and (string-match "^\\+[1-9][0-9]*$" str)
  582.        (string-to-int str)))
  583.  
  584.  
  585. (defun shell-dirtrack-toggle ()
  586.   "Turn directory tracking on and off in a shell buffer."
  587.   (interactive)
  588.   (if (setq shell-dirtrackp (not shell-dirtrackp))
  589.       (setq list-buffers-directory default-directory)
  590.     (setq list-buffers-directory nil))
  591.   (message "Directory tracking %s" (if shell-dirtrackp "ON" "OFF")))
  592.  
  593. ;;; For your typing convenience:
  594. (defalias 'dirtrack-toggle 'shell-dirtrack-toggle)
  595.  
  596. (defun shell-cd (dir)
  597.   "Do normal `cd' to DIR, and set `list-buffers-directory'."
  598.   (if shell-dirtrackp
  599.       (setq list-buffers-directory (file-name-as-directory
  600.                     (expand-file-name dir))))
  601.   (cd dir))
  602.  
  603. (defun shell-resync-dirs ()
  604.   "Resync the buffer's idea of the current directory stack.
  605. This command queries the shell with the command bound to 
  606. `shell-dirstack-query' (default \"dirs\"), reads the next
  607. line output and parses it to form the new directory stack.
  608. DON'T issue this command unless the buffer is at a shell prompt.
  609. Also, note that if some other subprocess decides to do output
  610. immediately after the query, its output will be taken as the
  611. new directory stack -- you lose. If this happens, just do the
  612. command again."
  613.   (interactive)
  614.   (let* ((proc (get-buffer-process (current-buffer)))
  615.      (pmark (process-mark proc)))
  616.     (goto-char pmark)
  617.     (insert shell-dirstack-query) (insert "\n")
  618.     (sit-for 0) ; force redisplay
  619.     (comint-send-string proc shell-dirstack-query) 
  620.     (comint-send-string proc "\n")
  621.     (set-marker pmark (point))
  622.     (let ((pt (point))) ; wait for 1 line
  623.       ;; This extra newline prevents the user's pending input from spoofing us.
  624.       (insert "\n") (backward-char 1)
  625.       (while (not (looking-at ".+\n"))
  626.     (accept-process-output proc)
  627.     (goto-char pt)))
  628.     (goto-char pmark) (delete-char 1) ; remove the extra newline
  629.     ;; That's the dirlist. grab it & parse it.
  630.     (let* ((dl (buffer-substring (match-beginning 0) (1- (match-end 0))))
  631.        (dl-len (length dl))
  632.        (ds '())            ; new dir stack
  633.        (i 0))
  634.       (while (< i dl-len)
  635.     ;; regexp = optional whitespace, (non-whitespace), optional whitespace
  636.     (string-match "\\s *\\(\\S +\\)\\s *" dl i) ; pick off next dir
  637.     (setq ds (cons (concat comint-file-name-prefix
  638.                    (substring dl (match-beginning 1)
  639.                       (match-end 1)))
  640.                ds))
  641.     (setq i (match-end 0)))
  642.       (let ((ds (nreverse ds)))
  643.     (condition-case nil
  644.         (progn (shell-cd (car ds))
  645.            (setq shell-dirstack (cdr ds)
  646.              shell-last-dir (car shell-dirstack))
  647.            (shell-dirstack-message))
  648.       (error (message "Couldn't cd.")))))))
  649.  
  650. ;;; For your typing convenience:
  651. (defalias 'dirs 'shell-resync-dirs)
  652.  
  653.  
  654. ;;; Show the current dirstack on the message line.
  655. ;;; Pretty up dirs a bit by changing "/usr/jqr/foo" to "~/foo".
  656. ;;; (This isn't necessary if the dirlisting is generated with a simple "dirs".)
  657. ;;; All the commands that mung the buffer's dirstack finish by calling
  658. ;;; this guy.
  659. (defun shell-dirstack-message ()
  660.   (let* ((msg "")
  661.      (ds (cons default-directory shell-dirstack))
  662.      (home (expand-file-name (concat comint-file-name-prefix "~/")))
  663.      (homelen (length home)))
  664.     (while ds
  665.       (let ((dir (car ds)))
  666.     (and (>= (length dir) homelen) (string= home (substring dir 0 homelen))
  667.         (setq dir (concat "~/" (substring dir homelen))))
  668.     ;; Strip off comint-file-name-prefix if present.
  669.     (and comint-file-name-prefix
  670.          (>= (length dir) (length comint-file-name-prefix))
  671.          (string= comint-file-name-prefix
  672.               (substring dir 0 (length comint-file-name-prefix)))
  673.          (setq dir (substring dir (length comint-file-name-prefix)))
  674.          (setcar ds dir))
  675.     (setq msg (concat msg (directory-file-name dir) " "))
  676.     (setq ds (cdr ds))))
  677.     (message "%s" msg)))
  678.  
  679. (defun shell-forward-command (&optional arg)
  680.   "Move forward across ARG shell command(s).  Does not cross lines.
  681. See `shell-command-regexp'."
  682.   (interactive "p")
  683.   (let ((limit (save-excursion (end-of-line nil) (point))))
  684.     (if (re-search-forward (concat shell-command-regexp "\\([;&|][\t ]*\\)+")
  685.                limit 'move arg)
  686.     (skip-syntax-backward " "))))
  687.  
  688.  
  689. (defun shell-backward-command (&optional arg)
  690.   "Move backward across ARG shell command(s).  Does not cross lines.
  691. See `shell-command-regexp'."
  692.   (interactive "p")
  693.   (let ((limit (save-excursion (comint-bol nil) (point))))
  694.     (if (> limit (point))
  695.     (save-excursion (beginning-of-line) (setq limit (point))))
  696.     (skip-syntax-backward " " limit)
  697.     (if (re-search-backward
  698.      (format "[;&|]+[\t ]*\\(%s\\)" shell-command-regexp) limit 'move arg)
  699.     (progn (goto-char (match-beginning 1))
  700.            (skip-chars-forward ";&|")))))
  701.  
  702.  
  703. (defun shell-dynamic-complete-command ()
  704.   "Dynamically complete the command at point.
  705. This function is similar to `comint-dynamic-complete-filename', except that it
  706. searches `exec-path' (minus the trailing emacs library path) for completion
  707. candidates.  Note that this may not be the same as the shell's idea of the
  708. path.
  709.  
  710. Completion is dependent on the value of `shell-completion-execonly', plus
  711. those that effect file completion.  See `shell-dynamic-complete-as-command'.
  712.  
  713. Returns t if successful."
  714.   (interactive)
  715.   (let ((filename (comint-match-partial-filename)))
  716.     (if (and filename
  717.          (save-match-data (not (string-match "[~/]" filename)))
  718.          (eq (match-beginning 0)
  719.          (save-excursion (shell-backward-command 1) (point))))
  720.     (prog2 (message "Completing command name...")
  721.         (shell-dynamic-complete-as-command)))))
  722.  
  723.  
  724. (defun shell-dynamic-complete-as-command ()
  725.   "Dynamically complete at point as a command.
  726. See `shell-dynamic-complete-filename'.  Returns t if successful."
  727.   (let* ((filename (or (comint-match-partial-filename) ""))
  728.      (pathnondir (file-name-nondirectory filename))
  729.      (paths (cdr (reverse exec-path)))
  730.      (cwd (file-name-as-directory (expand-file-name default-directory)))
  731.      (ignored-extensions
  732.       (and comint-completion-fignore
  733.            (mapconcat (function (lambda (x) (concat (regexp-quote x) "$")))
  734.               comint-completion-fignore "\\|")))
  735.      (path "") (comps-in-path ()) (file "") (filepath "") (completions ()))
  736.     ;; Go thru each path in the search path, finding completions.
  737.     (while paths
  738.       (setq path (file-name-as-directory (comint-directory (or (car paths) ".")))
  739.         comps-in-path (and (file-accessible-directory-p path)
  740.                    (file-name-all-completions pathnondir path)))
  741.       ;; Go thru each completion found, to see whether it should be used.
  742.       (while comps-in-path
  743.     (setq file (car comps-in-path)
  744.           filepath (concat path file))
  745.     (if (and (not (member file completions))
  746.          (not (and ignored-extensions
  747.                (string-match ignored-extensions file)))
  748.          (or (string-equal path cwd)
  749.              (not (file-directory-p filepath)))
  750.          (or (null shell-completion-execonly)
  751.              (file-executable-p filepath)))
  752.         (setq completions (cons file completions)))
  753.     (setq comps-in-path (cdr comps-in-path)))
  754.       (setq paths (cdr paths)))
  755.     ;; OK, we've got a list of completions.
  756.     (let ((success (let ((comint-completion-addsuffix nil))
  757.              (comint-dynamic-simple-complete pathnondir completions))))
  758.       (if (and (memq success '(sole shortest)) comint-completion-addsuffix
  759.            (not (file-directory-p (comint-match-partial-filename))))
  760.       (insert " "))
  761.       success)))
  762.  
  763.  
  764. (defun shell-match-partial-variable ()
  765.   "Return the shell variable at point, or nil if none is found."
  766.   (save-excursion
  767.     (let ((limit (point)))
  768.       (if (re-search-backward "[^A-Za-z0-9_{}]" nil 'move)
  769.       (or (looking-at "\\$") (forward-char 1)))
  770.       ;; Anchor the search forwards.
  771.       (if (or (eolp) (looking-at "[^A-Za-z0-9_{}$]"))
  772.       nil
  773.     (re-search-forward "\\$?{?[A-Za-z0-9_]*}?" limit)
  774.     (buffer-substring (match-beginning 0) (match-end 0))))))
  775.  
  776.  
  777. (defun shell-dynamic-complete-environment-variable ()
  778.   "Dynamically complete the environment variable at point.
  779. Completes if after a variable, i.e., if it starts with a \"$\".
  780. See `shell-dynamic-complete-as-environment-variable'.
  781.  
  782. This function is similar to `comint-dynamic-complete-filename', except that it
  783. searches `process-environment' for completion candidates.  Note that this may
  784. not be the same as the interpreter's idea of variable names.  The main problem
  785. with this type of completion is that `process-environment' is the environment
  786. which Emacs started with.  Emacs does not track changes to the environment made
  787. by the interpreter.  Perhaps it would be more accurate if this function was
  788. called `shell-dynamic-complete-process-environment-variable'.
  789.  
  790. Returns non-nil if successful."
  791.   (interactive)
  792.   (let ((variable (shell-match-partial-variable)))
  793.     (if (and variable (string-match "^\\$" variable))
  794.     (prog2 (message "Completing variable name...")
  795.         (shell-dynamic-complete-as-environment-variable)))))
  796.  
  797.  
  798. (defun shell-dynamic-complete-as-environment-variable ()
  799.   "Dynamically complete at point as an environment variable.
  800. Used by `shell-dynamic-complete-environment-variable'.
  801. Uses `comint-dynamic-simple-complete'."
  802.   (let* ((var (or (shell-match-partial-variable) ""))
  803.      (variable (substring var (or (string-match "[^$({]\\|$" var) 0)))
  804.      (variables (mapcar (function (lambda (x)
  805.                     (substring x 0 (string-match "=" x))))
  806.                 process-environment))
  807.      (addsuffix comint-completion-addsuffix)
  808.      (comint-completion-addsuffix nil)
  809.      (success (comint-dynamic-simple-complete variable variables)))
  810.     (if (memq success '(sole shortest))
  811.     (let* ((var (shell-match-partial-variable))
  812.            (variable (substring var (string-match "[^$({]" var)))
  813.            (protection (cond ((string-match "{" var) "}")
  814.                  ((string-match "(" var) ")")
  815.                  (t "")))
  816.            (suffix (cond ((null addsuffix) "")
  817.                  ((file-directory-p
  818.                    (comint-directory (getenv variable))) "/")
  819.                  (t " "))))
  820.       (insert protection suffix)))
  821.     success))
  822.  
  823.  
  824. (defun shell-replace-by-expanded-directory ()
  825.   "Expand directory stack reference before point.
  826. Directory stack references are of the form \"=digit\" or \"=-\".
  827. See `default-directory' and `shell-dirstack'.
  828.  
  829. Returns t if successful."
  830.   (interactive)
  831.   (if (comint-match-partial-filename)
  832.       (save-excursion
  833.     (goto-char (match-beginning 0))
  834.     (let ((stack (cons default-directory shell-dirstack))
  835.           (index (cond ((looking-at "=-/?")
  836.                 (length shell-dirstack))
  837.                ((looking-at "=\\([0-9]+\\)")
  838.                 (string-to-number
  839.                  (buffer-substring
  840.                   (match-beginning 1) (match-end 1)))))))
  841.       (cond ((null index)
  842.          nil)
  843.         ((>= index (length stack))
  844.          (error "Directory stack not that deep."))
  845.         (t
  846.          (replace-match (file-name-as-directory (nth index stack)) t t)
  847.          (message "Directory item: %d" index)
  848.          t))))))
  849.  
  850. (provide 'shell)
  851.  
  852. ;;; shell.el ends here
  853.